package com.crystal.jcms.utils;

import java.io.IOException;
import java.util.Map;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.Context;

public class HttpUtils {
	public interface CallBack {
		void onRequestComplete(String result);
	}

	public static void doPostAsyn(final Context context, final String method, final Map<String, String> param,
			final CallBack callBack) throws Exception {
		new Thread() {
			public void run() {
				try {
					String result = doPost(context, method, param);
					if (callBack != null) {
						callBack.onRequestComplete(result);
					}
				} catch (Exception e) {
					e.printStackTrace();
					if (callBack != null) {
						callBack.onRequestComplete(e.getMessage());
					}
				}
			};
		}.start();
	}

	public static String doPost(Context context, String method, Map<String, String> param) {
		String result = "";
		if (!NetUtils.isConnected(context)) {
			result = "500_网络异常!";
			return result;
		}
		// 命名空间
		String nameSpace = "http://tempuri.org/";
		// 调用的方法名称
		String methodName = method;
		String strUrl = "http://192.168.88.100/shpz/Shpz.asmx";
		// EndPoint
		String endPoint = strUrl;
		// SOAP Action
		String soapAction = "http://tempuri.org/" + method;

		// 指定WebService的命名空间和调用的方法名
		SoapObject rpc = new SoapObject(nameSpace, methodName);

		// 设置需调用WebService接口需要传入的参数
		if (param != null) {
			for (Map.Entry<String, String> entry : param.entrySet()) {
				String key = entry.getKey();
				String val = entry.getValue();
				rpc.addProperty(key, val);
			}
		}

		// 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);

		envelope.bodyOut = rpc;
		// 设置是否调用的是dotNet开发的WebService
		envelope.dotNet = true;
		// 等价于envelope.bodyOut = rpc; 
		envelope.setOutputSoapObject(rpc);

		HttpTransportSE transport = new HttpTransportSE(endPoint);
		try {
			// 调用WebService
			transport.call(soapAction, envelope);
			// 获取返回的数据
			SoapObject object = (SoapObject) envelope.bodyIn;
			// 获取返回的结果
			result = object.getProperty(0).toString();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				transport.call(soapAction, envelope);
			} catch (HttpResponseException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (XmlPullParserException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			result = "501_"+e.getMessage();
			return result;
		}
		return result;
	}
}
